{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dfe37963-1af6-44fc-a841-8e462443f5e6",
   "metadata": {},
   "source": [
    "## Expert Knowledge Worker\n",
    "\n",
    "Features:\n",
    "- A question answering agent that is an expert knowledge worker\n",
    "- To be used by employees of Insurellm, an Insurance Tech company\n",
    "- The agent needs to be accurate and the solution should be low cost.\n",
    "\n",
    "This project will use RAG (Retrieval Augmented Generation) to ensure our question/answering assistant has high accuracy.\n",
    "\n",
    "Technology:\n",
    "- RAG: LangChain\n",
    "- Embedding model: OpenAIEmbeddings or HuggingFace sentence-transformers\n",
    "- Encoding method: Auto-encoding\n",
    "- Vector datastore: Chroma or FAISS\n",
    "- Vector DB visualization: Plotly\n",
    "- Dimensionality reduction technique: t-SNE\n",
    "\n",
    "# Dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "802137aa-8a74-45e0-a487-d1974927d7ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "# imports\n",
    "\n",
    "import os\n",
    "import glob\n",
    "from dotenv import load_dotenv\n",
    "import gradio as gr\n",
    "from langchain.document_loaders import DirectoryLoader, TextLoader\n",
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain.schema import Document\n",
    "from langchain_openai import OpenAIEmbeddings, ChatOpenAI\n",
    "from langchain.embeddings import HuggingFaceEmbeddings\n",
    "from langchain_chroma import Chroma\n",
    "from langchain.vectorstores import FAISS\n",
    "import numpy as np\n",
    "from sklearn.manifold import TSNE\n",
    "import plotly.graph_objects as go\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "from langchain.chains import ConversationalRetrievalChain"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7187c181-5b17-4df7-b298-b7cb2b6d09f7",
   "metadata": {},
   "source": [
    "# Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58c85082-e417-4708-9efe-81a5d55d1424",
   "metadata": {},
   "outputs": [],
   "source": [
    "MODEL = \"gpt-4o-mini\"\n",
    "db_name = \"vector_db\"\n",
    "db_type = \"Chroma\"\n",
    "# db_type = \"FAISS\"\n",
    "embed_type = \"OpenAIEmbeddings\"\n",
    "# embed_type = \"sentence-transformers\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee78efcb-60fe-449e-a944-40bab26261af",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load environment variables\n",
    "\n",
    "load_dotenv(override=True)\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2f0866b-5cfb-4ecd-87d1-6da872887dcd",
   "metadata": {},
   "source": [
    "# Create Knowledge Base for RAG\n",
    "\n",
    "## Load Company Documents\n",
    "\n",
    "Uses LangChain to read in a Knowledge Base of documents and to divide up documents into overlaping chunks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "730711a9-6ffe-4eee-8f48-d6cfb7314905",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Read in documents using LangChain's loaders\n",
    "# Take everything in all the sub-folders of our knowledgebase\n",
    "\n",
    "folders = glob.glob(\"../knowledge-base/*\")\n",
    "text_loader_kwargs = {'encoding': 'utf-8'}\n",
    "# text_loader_kwargs={'autodetect_encoding': True}\n",
    "\n",
    "documents = []\n",
    "for folder in folders:\n",
    "    doc_type = os.path.basename(folder)\n",
    "    loader = DirectoryLoader(folder, glob=\"**/*.md\", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)\n",
    "    folder_docs = loader.load()\n",
    "    for doc in folder_docs:\n",
    "        doc.metadata[\"doc_type\"] = doc_type\n",
    "        documents.append(doc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7310c9c8-03c1-4efc-a104-5e89aec6db1a",
   "metadata": {},
   "outputs": [],
   "source": [
    "text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
    "chunks = text_splitter.split_documents(documents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd06e02f-6d9b-44cc-a43d-e1faa8acc7bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "len(chunks)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c54b4b6-06da-463d-bee7-4dd456c2b887",
   "metadata": {},
   "outputs": [],
   "source": [
    "doc_types = set(chunk.metadata['doc_type'] for chunk in chunks)\n",
    "print(f\"Document types found: {', '.join(doc_types)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77f7d2a6-ccfa-425b-a1c3-5e55b23bd013",
   "metadata": {},
   "source": [
    "## Vector Embeddings\n",
    "\n",
    "Convert chunks of text into Vectors using OpenAIEmbeddings and store the Vectors in Chroma (or FAISS)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78998399-ac17-4e28-b15f-0b5f51e6ee23",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Put the chunks of data into a Vector Store that associates a Vector Embedding with each chunk\n",
    "\n",
    "embeddings = None\n",
    "# OpenAIEmbeddings is OpenAI's vector embedding models\n",
    "if embed_type == \"OpenAIEmbeddings\":\n",
    "    embeddings = OpenAIEmbeddings()\n",
    "\n",
    "# sentence-transformers is a free Vector embeddings model from HuggingFace\n",
    "elif embed_type == \"sentence-transformers\":\n",
    "    embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-MiniLM-L6-v2\")\n",
    "\n",
    "if embeddings is None:\n",
    "    print(\"ERROR: embeddings not set. Check embed_type is set to a valid model\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64768521-a775-472c-83c5-0c0d715d44ac",
   "metadata": {},
   "source": [
    "## Create Vector Datastore"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "057868f6-51a6-4087-94d1-380145821550",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create vectorstore\n",
    "vectorstore = None\n",
    "\n",
    "# Chroma is a popular open source Vector Database based on SQLLite\n",
    "if db_type == \"Chroma\":\n",
    "    # Delete vector DB if already exists\n",
    "    if os.path.exists(db_name):\n",
    "        Chroma(persist_directory=db_name, embedding_function=embeddings).delete_collection()\n",
    "    \n",
    "    # Create vectorstore\n",
    "    vectorstore = Chroma.from_documents(documents=chunks, embedding=embeddings, persist_directory=db_name)\n",
    "    \n",
    "    print(f\"Vectorstore created with {vectorstore._collection.count()} documents\")\n",
    "\n",
    "    # Get one vector and find how many dimensions it has\n",
    "    collection = vectorstore._collection\n",
    "    sample_embedding = collection.get(limit=1, include=[\"embeddings\"])[\"embeddings\"][0]\n",
    "    dimensions = len(sample_embedding)\n",
    "    print(f\"The vectors have {dimensions:,} dimensions\")\n",
    "    \n",
    "# FAISS is an in-memory vector DB from Facebook\n",
    "elif db_type == \"FAISS\":\n",
    "    # Create vectorstore\n",
    "    vectorstore = FAISS.from_documents(chunks, embedding=embeddings)\n",
    "    \n",
    "    total_vectors = vectorstore.index.ntotal\n",
    "    dimensions = vectorstore.index.d\n",
    "    print(f\"There are {total_vectors} vectors with {dimensions:,} dimensions in the vector store\")\n",
    "\n",
    "else:\n",
    "    print(\"ERROR: Vector datastore not created. Check db_type is set to a valid database\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0d45462-a818-441c-b010-b85b32bcf618",
   "metadata": {},
   "source": [
    "# Visualizing the Vector Store\n",
    "\n",
    "Humans are not very good at visualizing things with more than 3 dimensions so to visualize a vector datastore with thousands of dimesions. We need to use techniques like projecting down to reduce the dimensions to only 2 or 3 dimensions in a way that does the best possible job at separating things out to stay faithful to the multi-dimensional representation.\n",
    "\n",
    "For example, things that are far apart in these multiple dimensions will still be far apart even when projected down to 2 dimensions.\n",
    "\n",
    "[t-distributed stochastic neighbor embedding (t-SNE)](https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding) is a nonlinear dimensionality reduction technique for embedding high-dimensional data for visualization in a low-dimensional space of two or three dimensions.\n",
    "\n",
    "## Configure Visualization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b98adf5e-d464-4bd2-9bdf-bc5b6770263b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prework\n",
    "if db_type == \"Chroma\":\n",
    "    result = collection.get(include=['embeddings', 'documents', 'metadatas'])\n",
    "    vectors = np.array(result['embeddings'])\n",
    "    documents = result['documents']\n",
    "    doc_types = [metadata['doc_type'] for metadata in result['metadatas']]\n",
    "    colors = [['blue', 'green', 'red', 'orange'][['products', 'employees', 'contracts', 'company'].index(t)] for t in doc_types]\n",
    "\n",
    "elif db_type == \"FAISS\":\n",
    "    vectors = []\n",
    "    documents = []\n",
    "    doc_types = []\n",
    "    colors = []\n",
    "    color_map = {'products':'blue', 'employees':'green', 'contracts':'red', 'company':'orange'}\n",
    "    \n",
    "    for i in range(total_vectors):\n",
    "        vectors.append(vectorstore.index.reconstruct(i))\n",
    "        doc_id = vectorstore.index_to_docstore_id[i]\n",
    "        document = vectorstore.docstore.search(doc_id)\n",
    "        documents.append(document.page_content)\n",
    "        doc_type = document.metadata['doc_type']\n",
    "        doc_types.append(doc_type)\n",
    "        colors.append(color_map[doc_type])\n",
    "        \n",
    "    vectors = np.array(vectors)\n",
    "\n",
    "else:\n",
    "    print(\"ERROR: Vector datastore not created. Check db_type is set to a valid database\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb279701-0086-44aa-a2da-14341aecf529",
   "metadata": {},
   "source": [
    "## Reduce the dimensionality to 2D"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "427149d5-e5d8-4abd-bb6f-7ef0333cca21",
   "metadata": {},
   "outputs": [],
   "source": [
    "# We humans find it easier to visalize things in 2D!\n",
    "# Reduce the dimensionality of the vectors to 2D using t-SNE\n",
    "# (t-distributed stochastic neighbor embedding)\n",
    "\n",
    "tsne = TSNE(n_components=2, random_state=42)\n",
    "reduced_vectors = tsne.fit_transform(vectors)\n",
    "\n",
    "# Create the 2D scatter plot\n",
    "fig = go.Figure(data=[go.Scatter(\n",
    "    x=reduced_vectors[:, 0],\n",
    "    y=reduced_vectors[:, 1],\n",
    "    mode='markers',\n",
    "    marker=dict(size=5, color=colors, opacity=0.8),\n",
    "    text=[f\"Type: {t}<br>Text: {d[:100]}...\" for t, d in zip(doc_types, documents)],\n",
    "    hoverinfo='text'\n",
    ")])\n",
    "\n",
    "fig.update_layout(\n",
    "    title=f'2D {db_type} Vector Store Visualization',\n",
    "    scene=dict(xaxis_title='x',yaxis_title='y'),\n",
    "    width=800,\n",
    "    height=600,\n",
    "    margin=dict(r=20, b=10, l=10, t=40)\n",
    ")\n",
    "\n",
    "fig.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2b724f3-e3ad-4d42-bfa4-a89386d6414e",
   "metadata": {},
   "source": [
    "## Reduce the dimensionality to 3D"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e1418e88-acd5-460a-bf2b-4e6efc88e3dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3D representation isn't as easy to navigate\n",
    "\n",
    "tsne = TSNE(n_components=3, random_state=42)\n",
    "reduced_vectors = tsne.fit_transform(vectors)\n",
    "\n",
    "# Create the 3D scatter plot\n",
    "fig = go.Figure(data=[go.Scatter3d(\n",
    "    x=reduced_vectors[:, 0],\n",
    "    y=reduced_vectors[:, 1],\n",
    "    z=reduced_vectors[:, 2],\n",
    "    mode='markers',\n",
    "    marker=dict(size=5, color=colors, opacity=0.8),\n",
    "    text=[f\"Type: {t}<br>Text: {d[:100]}...\" for t, d in zip(doc_types, documents)],\n",
    "    hoverinfo='text'\n",
    ")])\n",
    "\n",
    "fig.update_layout(\n",
    "    title=f'3D {db_type} Vector Store Visualization',\n",
    "    scene=dict(xaxis_title='x', yaxis_title='y', zaxis_title='z'),\n",
    "    width=900,\n",
    "    height=700,\n",
    "    margin=dict(r=20, b=10, l=10, t=40)\n",
    ")\n",
    "\n",
    "fig.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9468860b-86a2-41df-af01-b2400cc985be",
   "metadata": {},
   "source": [
    "# Expert Knowledge Worker\n",
    "\n",
    "Use LangChain to bring it all together by creating a conversation chain with RAG and memory.\n",
    "\n",
    "Key abstractions in LangChain:\n",
    "- LLM: represents abstraction around a model\n",
    "- Retriever: interface onto somthing like a vector store used for RAG retrieval\n",
    "- Memory: represents a history of a conversation with a chatbot in memory\n",
    "\n",
    "Because LangChain abstracts the reprentation of the LLM, retriever and memory the code is the same for any model and knowledge base.\n",
    "\n",
    "Note: ok to ignore _Deprecation Warning_ for now; LangChain are not expected to remove ConversationBufferMemory any time soon.\n",
    "\n",
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "129c7d1e-0094-4479-9459-f9360b95f244",
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a new Chat with OpenAI\n",
    "llm = ChatOpenAI(temperature=0.7, model_name=MODEL)\n",
    "\n",
    "# set up the conversation memory for the chat\n",
    "memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)\n",
    "\n",
    "# the retriever is an abstraction over the VectorStore that will be used during RAG\n",
    "retriever = vectorstore.as_retriever()\n",
    "\n",
    "# putting it together: set up the conversation chain with the GPT 4o-mini LLM, the vector store and memory\n",
    "conversation_chain = ConversationalRetrievalChain.from_llm(llm=llm, retriever=retriever, memory=memory)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "968e7bf2-e862-4679-a11f-6c1efb6ec8ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"Can you describe Insurellm in a few sentences\"\n",
    "result = conversation_chain.invoke({\"question\":query})\n",
    "print(result[\"answer\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "990a2917-562c-461a-8ce9-a8ad8ad1646d",
   "metadata": {},
   "source": [
    "## Clear Memory\n",
    "\n",
    "Clear the memory from the testing and restart conversation chain for UI."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6eb99fb-33ec-4025-ab92-b634ede03647",
   "metadata": {},
   "outputs": [],
   "source": [
    "# clear the memory and restart conversation chain for UI\n",
    "memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)\n",
    "conversation_chain = ConversationalRetrievalChain.from_llm(llm=llm, retriever=retriever, memory=memory)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bbbcb659-13ce-47ab-8a5e-01b930494964",
   "metadata": {},
   "source": [
    "## Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c3536590-85c7-4155-bd87-ae78a1467670",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Wrapping in a function - note that history isn't used, as the memory is in the conversation_chain\n",
    "\n",
    "def chat(message, history):\n",
    "    result = conversation_chain.invoke({\"question\": message})\n",
    "    return result[\"answer\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b655d3da-277b-45a9-8113-747314ec0889",
   "metadata": {},
   "source": [
    "## UI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b252d8c1-61a8-406d-b57a-8f708a62b014",
   "metadata": {},
   "outputs": [],
   "source": [
    "# And in Gradio:\n",
    "\n",
    "view = gr.ChatInterface(chat, type=\"messages\", examples=[\"what is insurellm?\",\"what did avery do before?\", \"does insurellm offer any products in the auto industry space?\"], title=\"Insurellm Expert Knowledge Worker\").launch(inbrowser=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5435b2b9-935c-48cd-aaf3-73a837ecde49",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
